package com.fone.player.activity.personal;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.BaseFragment;
import com.fone.player.activity.local.SortListUtil;
import com.fone.player.activity.main.MainTabActivity;
import com.fone.player.activity.personal.adapter.QuickPlayAdapter;
import com.fone.player.activity.personal.adapter.QuickPlayAdapter.ViewHolder;
import com.fone.player.bean.RecordData;
import com.fone.player.cache.ImageDownloadModule;
import com.fone.player.client.Callback;
import com.fone.player.client.CollectionRst;
import com.fone.player.client.CollectionlsRst;
import com.fone.player.client.CollectionlsRst.Cnt;
import com.fone.player.client.Configure;
import com.fone.player.client.Error;
import com.fone.player.client.Reporter;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.CacheVideo;
import com.fone.player.entity.OfflineCache;
import com.fone.player.entity.PlayRecord;
import com.fone.player.play.FonePlayerActivity;
import com.fone.player.play.PlayerAction;
import com.fone.player.play.PlayerFrom;
import com.fone.player.play.WebPlayerFrom;
import com.fone.player.sns.ISNSShareManager.ShareStateListener;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.sns.bean.SNSUserInfo;
import com.fone.player.sns.bean.ShareInfo;
import com.fone.player.sns.impl.SNSShareManager;
import com.fone.player.storage.SharedPreferenceModule;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;
import com.fone.player.util.deleteHistoryAnimationUtil;
import com.fone.player.view.ColorBallProgressView;
import com.fone.player.view.LocalDeleteMediaDialog;
import com.fone.player.view.LocalDeleteMediaDialog.IDeleteListener;
import com.fone.player.view.QuickPlayMoreOperationPopWindow;
import com.fone.player.view.QuickPlayMoreOperationPopWindow.IMoreOperationListener;
import com.fone.player.view.SelectSharePopwindow;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

/**
 * 
 * 快速播放(播放记录)
 * 
 * @author gjl
 * @since 2014-5-30
 */
public class PlayRecordFragment extends BaseFragment implements OnClickListener {

	private static String TAG = "PlayFragment";
	private View mView;
	private ListView lv_quick_play_video;
	private List<PlayRecord> mHistoryRecords, mTempHistoryRecords;
	private PlayRecord mHeaderRecord;
	private QuickPlayAdapter mAdapter;
	private Button btn_clear_all;
	private ImageView iv_quick_play_pucker;
	private ImageView iv_quick_play_more;
	private SelectSharePopwindow mSelectSharePopwindow;
	private View rl_quick_play_video;
	private MyShareStateListener mShareStateListener;
	private View recordView;
	private View noRecordView;
	private TextView tv_login_tip;
	private IPlayFragmentCallBack CallBack;
	private TextView header_tv_quick_play_time;
	private ImageView iv_header;
	private ImageView iv_quick_play_start;
	private Handler mHandler;
	private List<PlayRecord> mDeleteList;
	private static List<PlayRecord> mAddList;
	public static final int DELETE = 0, SHARE = 1, DETAIL = 2, COLLECT = 3;

	public static final int REFRASHDATA = 4;
	private static final int FULLPLAYER = 0, DETAILPLAYER = 1;
	private View rl_login_tip;
	private TextView tv_go_online;
	private boolean isDeleteHeader;
	private ProgressBar header_pb_quick_play;
	private deleteQuickPlayCallBack deleteCallBack;
	private int SUCCESS = 0;
	private View loadingView;
	private ColorBallProgressView loadView;
	private static int MAXNUM = 20;// 播放记录上限
	private boolean mNeedRefrushRecordFomeServer = true;

	private long preClickTime = 0l;

	private boolean foreground = false;

	private static PlayRecordFragment f;

	public void setCallBack(IPlayFragmentCallBack callBack) {

		CallBack = callBack;
	}

	public static PlayRecordFragment newInstance() {
		if (f == null) {
			f = new PlayRecordFragment();
		}
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater
					.inflate(R.layout.quick_play_view, container, false);
		}
		ViewGroup parent = (ViewGroup) mView.getParent();
		if (parent != null) {
			parent.removeView(mView);
		}
		initHandler();
		initView();
		// initData();
		return mView;
	}

	@SuppressLint("HandlerLeak")
	private void initHandler() {
		mHandler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				super.dispatchMessage(msg);
				switch (msg.what) {
				case DELETE:
					int postion = msg.arg1;
					View view = (View) msg.obj;
					doDelete(mHistoryRecords.get(postion), view, postion);
					break;
				case SHARE:
					int sharePosition = msg.arg1;
					showSharePopWindow(mHistoryRecords.get(sharePosition));
					break;
				case DETAIL:
					int detailPosition = msg.arg1;
					doDetail(mHistoryRecords.get(detailPosition));
					break;
				case COLLECT:
					int collectionPosition = msg.arg1;
					PlayRecord record = mHistoryRecords.get(collectionPosition);
					doCollection(record);// 收藏
					break;
				case REFRASHDATA:
					L.v(TAG, "initHandler",
							"receive msg and PlayRecordFragment is foreground : "
									+ f.foreground);
					if (f.foreground) {
						f.initData();
					}
					break;

				default:
					break;
				}
			}
		};
	}

	// 进入详情页
	protected void doDetail(PlayRecord historyPlayRecord) {
		gotoPlayer(historyPlayRecord, DETAILPLAYER);
	}

	private synchronized void initData() {
		boolean hasLogin = UserInfoManager.isLogin();
		L.i(TAG, "onresume", "hasLogin:" + hasLogin);
		L.i(TAG, "onresume", "FoneConstant.isLogin:" + FoneConstant.isLogin);
		if (hasLogin && !FoneConstant.isLogin) {// 从未登录到登陆 需要从服务器获取数据
			FoneConstant.isLogin = true;
			mNeedRefrushRecordFomeServer = true;
			initMyData(mNeedRefrushRecordFomeServer);
		} else {
			mNeedRefrushRecordFomeServer = false;
			// 从数据库中获取数据
			initMyData(mNeedRefrushRecordFomeServer);
		}

	}

	// 从本地数据库获取记录
	private void getRecordfromDB(int type) {
		// 数据库取的播放记录
		ArrayList<PlayRecord> PlayRecords = StorageModule.getInstance()
				.getPlayRecordList(type);
		ArrayList<PlayRecord> tempRecords = new ArrayList<PlayRecord>();
		for (int i = 0; i < PlayRecords.size(); i++) {
			if (PlayRecords.get(i).getPlayRecordSynchronzieType() != PlayRecord.PLAY_RECORD_SYNCHRONZIE_DELETE_WAIT) {
				L.i(TAG, "getRecordfromDB:" + PlayRecords.get(i).toString());
				tempRecords.add(PlayRecords.get(i));
			}
		}
		L.i(TAG, "观看记录：PlayRecords size:" + PlayRecords.size());
		PlayRecords.clear();
		mTempHistoryRecords.addAll(tempRecords);
	}

	// 从服务器获取历史记录
	private void getRecordformServer() {
		if (mNeedRefrushRecordFomeServer) {
			loadingView.setVisibility(View.VISIBLE);
			loadView.setVisibility(View.VISIBLE);
		}
		ArrayList<PlayRecord> recordList = StorageModule.getInstance()
				.getPlayRecordList(PlayRecord.RECORD_WEB_ALL);
		List<RecordData> records = null;
		if (recordList != null) {
			records = new ArrayList<RecordData>();
			for (PlayRecord record : recordList) {
				if (record.getPlayRecordSynchronzieType() == 1
						|| record.getPlayRecordSynchronzieType() == 2) {
					RecordData data = new RecordData();
					data.ccid = record.getPlayRecordCCID();
					data.cid = record.getPlayRecordCID();
					data.clid = record.getPlayRecordCLID();
					data.videoid = record.getPlayRecordVideoID();
					data.type = record.getPlayRecordSynchronzieType();
					data.secs = record.getPlayRecordTotalTime();
					data.tp = record.getPlayRecordAlreadyPlayTime();
					data.updatetime = record.getPlayRecordCreateTime();
					records.add(data);
				}
			}
			L.i(TAG, "getRecordformServer record datas:" + records.toString());
		}

		QuickPlayCallBack callBack = new QuickPlayCallBack();
		// 向服务器同步播放记录，并获取播放记录
		if (records != null && records.size() > 0) {
			Request.getInstance().collectionls(1, 2, records, callBack);
		} else {
			Request.getInstance().collectionls(1, 2, null, callBack);
		}

	}

	// 展示没有记录的页面
	private void showNoRecordView() {
		if (UserInfoManager.isLogin()) {
			recordView.setVisibility(View.GONE);
			noRecordView.setVisibility(View.VISIBLE);
			rl_login_tip.setVisibility(View.GONE);
		} else {
			recordView.setVisibility(View.GONE);
			noRecordView.setVisibility(View.VISIBLE);
			rl_login_tip.setVisibility(View.VISIBLE);
		}
	}

	private void initView() {
		mHistoryRecords = new ArrayList<PlayRecord>();
		mTempHistoryRecords = new ArrayList<PlayRecord>();
		lv_quick_play_video = (ListView) mView
				.findViewById(R.id.lv_quick_play_video);
		if (lv_quick_play_video.getHeaderViewsCount() == 0
				&& getActivity() != null) {
			View view = new View(getActivity());
			lv_quick_play_video.addHeaderView(view);
		}
		rl_quick_play_video = mView.findViewById(R.id.rl_quick_play_video);
		rl_quick_play_video.setOnClickListener(this);
		recordView = mView.findViewById(R.id.rl_records);
		noRecordView = mView.findViewById(R.id.rl_no_records);
		noRecordView.setOnClickListener(this);
		tv_login_tip = (TextView) mView.findViewById(R.id.tv_login_tip);
		rl_login_tip = mView.findViewById(R.id.rl_login_tip);
		tv_login_tip = (TextView) mView.findViewById(R.id.tv_login_tip);
		tv_go_online = (TextView) mView.findViewById(R.id.tv_go_online);
		tv_login_tip.setOnClickListener(this);
		tv_go_online.setOnClickListener(this);
		loadView = (ColorBallProgressView) mView.findViewById(R.id.pb);
		loadingView = mView.findViewById(R.id.rl_quick_play_loading);

		if (lv_quick_play_video.getFooterViewsCount() <= 0) {
			btn_clear_all = new Button(getActivity());
			btn_clear_all.setText("清空");
			btn_clear_all.setTextColor(getResources().getColor(
					R.color.local_btn_more_video));
			btn_clear_all
					.setBackgroundResource(R.drawable.list_bg_base_selector);
			btn_clear_all.setHeight(ScreenUtil.dp2px(50));

			lv_quick_play_video.addFooterView(btn_clear_all);
		}
		iv_quick_play_start = (ImageView) mView
				.findViewById(R.id.iv_quick_play_start);
		iv_quick_play_start.setOnClickListener(this);
		header_tv_quick_play_time = (TextView) mView
				.findViewById(R.id.tv_quick_play_time);
		iv_header = (ImageView) mView.findViewById(R.id.iv_header);
		header_pb_quick_play = (ProgressBar) mView
				.findViewById(R.id.pb_quick_play);
		mAdapter = new QuickPlayAdapter(getActivity(), mHistoryRecords,
				mHandler);

		lv_quick_play_video.setAdapter(mAdapter);
		iv_quick_play_pucker = (ImageView) mView
				.findViewById(R.id.iv_quick_play_pucker);
		iv_quick_play_more = (ImageView) mView
				.findViewById(R.id.iv_quick_play_more);
		iv_quick_play_pucker.setOnClickListener(this);
		iv_quick_play_more.setOnClickListener(this);
		btn_clear_all.setOnClickListener(new clearListener());
		lv_quick_play_video.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				if (!isClickValid()) {// 点击是否有效
					return;
				}
				if (lv_quick_play_video.getHeaderViewsCount() > 0
						&& position > 0) {
					position = position - 1;
				}
				L.i(TAG, "onItemClick  position :" + position);
				PlayRecord record = mHistoryRecords.get(position);
				L.v(TAG, "onItemClick", record.getPlayRecordType());
				if (record.getPlayRecordType() != PlayRecord.RECORD_PLAYER_CACHE) {
					gotoPlayer(record, FULLPLAYER);
				} else {// 是缓存的视频
					L.v(TAG, "onItemClick", "RECORD_PLAYER_CACHE play !!!");
					ArrayList<CacheVideo> videos = new ArrayList<CacheVideo>();
					CacheVideo video = new CacheVideo();
					String[] urls = record.getOfflineCacheFragmentUrlArray();
					video.setUrls(urls);
					int[] durations = record
							.getOfflineCacheFragmentDurationArray();
					video.setDurations(durations);
					video.setName(record.getPlayRecordName());
					video.setXyzplay(record.getPlayRecordPlayUrl());
					video.setPic(record.getPlayRecordImageUrl());
					video.setDownFinish(true);
					videos.add(video);
					FoneUtil.openCacheVideo(getActivity(),
							PlayerFrom.CACHE_LIST, videos, 0);
				}
			}
		});
	}

	// 跳转到播放页面
	public void gotoPlayer(PlayRecord record, int mode) {
		L.i(TAG, "gotoPlayer", "Record:" + record.toString());
		L.i(TAG, "gotoPlayer", "mode:" + mode);
		if (record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL) {
			File file = new File(record.getPlayRecordPlayUrl());
			if (!file.exists()) {
				String nofile = getActivity().getResources().getString(
						R.string.player_full_file_not_exist);
				FoneUtil.showToast(getActivity(), nofile);
				StorageModule.getInstance().deletePlayRecord(record);
				if (record == mHeaderRecord) {
					if (mHistoryRecords.size() > 0) {
						mHeaderRecord = mHistoryRecords.remove(0);
						fillHeaderView();
					} else {
						showNoRecordView();
					}
				} else {
					mHistoryRecords.remove(record);
				}
				if (mHistoryRecords.size() == 0) {
					showClearButton(false);
				}
				mAdapter.notifyDataSetChanged();
				return;
			}
		}
		if ((record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_NETWORK || record
				.getPlayRecordType() == PlayRecord.RECORD_WEB_SOURCE)
				&& !FoneUtil.isNetOkWithToast(getActivity())) {
			return;
		}
		if (record.getPlayRecordType() == PlayRecord.RECORD_WEB_SOURCE
				&& mode == FULLPLAYER) {// 如果是源网页
			FoneUtil.open3rdPlayer(this.getActivity(),
					WebPlayerFrom.FASTPLAY, record.getPlayRecordExternalUrl(),
					record.getPlayRecordPlayUrl(), record.getPlayRecordName(),
					record.getPlayRecordIsShowPlayButton() ? 1 : 0,
					record.getPlayRecordShareUrl(),
					record.getPlayRecordImageUrl());
		} else {// 其他跳全屏
			Intent intent = new Intent(getActivity(), FonePlayerActivity.class);
			if (record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL) {
				intent.putExtra("from", PlayerFrom.FAST_PLAY_LOCAL);
			} else if (record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_NETWORK
					|| record.getPlayRecordType() == PlayRecord.RECORD_WEB_SOURCE) {
				intent.putExtra("from", PlayerFrom.FAST_PLAY_ONLINE);
			}
			if (mode == FULLPLAYER) {
				intent.putExtra("action", PlayerAction.FULLPLAY.name());
				intent.putExtra("xyzplay", record.getPlayRecordPlayUrl());
			} else if (mode == DETAILPLAYER) {
				intent.putExtra("action", PlayerAction.DETAIL.name());
				intent.putExtra("vgdetail", record.getPlayRecordDetailUrl());
			}
			intent.putExtra("name", record.getPlayRecordName());

			L.i(TAG, "mHistoryRecords url:" + record.getPlayRecordPlayUrl());
			L.i(TAG, "mHistoryRecords name:" + record.getPlayRecordName());
			startActivity(intent);
		}
	}

	// 填充头部数据
	private void fillHeaderView() {
		if (!foreground) { // 如果没有在前台
			return;
		}

		L.i(TAG, "fillHeaderView", "mHeaderRecord:" + mHeaderRecord);
		if (mHeaderRecord != null) {
			long min = (mHeaderRecord.getPlayRecordAlreadyPlayTime() / 1000) / 60;
			long sencond = (mHeaderRecord.getPlayRecordAlreadyPlayTime() / 1000) % 60;
			if (min != 0) {
				if (sencond < 10) {
					header_tv_quick_play_time.setText("您上次观看到" + min + "分0"
							+ sencond + "秒");
				} else {
					header_tv_quick_play_time.setText("您上次观看到" + min + "分"
							+ sencond + "秒");
				}
			} else {
				header_tv_quick_play_time.setText("您上次观看到" + sencond + "秒");
			}
			int progress = 0;
			if (mHeaderRecord.getPlayRecordTotalTime() != 0) {
				L.i(TAG,
						"PlayRecordTotalTime:"
								+ mHeaderRecord.getPlayRecordTotalTime());
				L.i(TAG,
						"PlayRecordAlreadyPlayTime:"
								+ mHeaderRecord.getPlayRecordAlreadyPlayTime());
				progress = (int) ((float) (mHeaderRecord
						.getPlayRecordAlreadyPlayTime())
						/ (float) (mHeaderRecord.getPlayRecordTotalTime()) * 100);
				header_pb_quick_play.setProgress(progress);

				MainTabActivity.mQuickPlayBtn.setProgress(progress);
				SharedPreferenceModule.getInstance().setInt(
						"play_record_progress", progress);

			}
			if (TextUtils.isEmpty(mHeaderRecord.getPlayRecordImageUrl())) {
				iv_header.setImageBitmap(null);
				iv_header.setImageDrawable(null);
				iv_header
						.setBackgroundResource(R.drawable.default_image_video_bg);
				L.i(TAG,
						"itemBean.pic:" + mHeaderRecord.getPlayRecordImageUrl());
			} else {

				if (getActivity() == null) {
					return;
				}
				if (mHeaderRecord.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL
						|| mHeaderRecord.getPlayRecordType() == PlayRecord.RECORD_PLAYER_CACHE) {
					int width = ScreenUtil.getScreenWidthPix(getActivity());
					int height = ScreenUtil.dp2px(284);

					ImageDownloadModule downloadModule = ImageDownloadModule
							.getInstance();

					// downloadModule.setHandler(mHandler,
					// mHeaderRecord.getPlayRecordImageUrl());
					downloadModule.display(
							mHeaderRecord.getPlayRecordImageUrl(), width,
							height, iv_header);
					downloadModule.display(
							mHeaderRecord.getPlayRecordImageUrl(), width,
							height, MainTabActivity.mPlayLayout);

					SharedPreferenceModule.getInstance().setBoolean(
							"play_record_local_url", true);
					SharedPreferenceModule.getInstance().setString(
							"play_record_url",
							mHeaderRecord.getPlayRecordImageUrl());

				} else if (!TextUtils.isEmpty(mHeaderRecord
						.getPlayRecordImageUrl())) {
					ImageDownloadModule downloadModule = ImageDownloadModule
							.getInstance();

					DisplayImageOptions mOptions = new DisplayImageOptions.Builder()
							.showImageForEmptyUri(
									R.drawable.default_image_video_bg)// 设置图片Uri为空或是错误的时候显示的图片
							.showImageOnFail(R.drawable.default_image_video_bg) // 设置图片加载/解码过程中错误时候显示的图片
							.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
							.cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
							.considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
							.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
							.bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
							// .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
							.build();// 构建完成

					downloadModule.download(
							mHeaderRecord.getPlayRecordImageUrl(), iv_header,
							mOptions);
					downloadModule.download(
							mHeaderRecord.getPlayRecordImageUrl(),
							R.drawable.home_quick_play_surface,
							MainTabActivity.mPlayLayout);

					SharedPreferenceModule.getInstance().setBoolean(
							"play_record_local_url", false);
					SharedPreferenceModule.getInstance().setString(
							"play_record_url",
							mHeaderRecord.getPlayRecordImageUrl());
				}
			}
		}
	}

	// 展示分享的popwindow
	private void showSharePopWindow(PlayRecord record) {

		ShareInfo info = new ShareInfo(
				SNSShareManager.TENCENT_WEIXIN_FRIEND_TYPE);
		String share_word_prefix = getResources().getString(
				R.string.select_share_word_prefix);
		String share_link_address = getResources().getString(
				R.string.select_share_link_address);
		info.title = record.getPlayRecordName();
		info.titleUrl = share_link_address;
		info.text = share_word_prefix + record.getPlayRecordName();
		info.videoUrl = FoneUtil.getAbsoluteUrl(Configure.getEndPoint()
				.substring(0, Configure.getEndPoint().lastIndexOf("/")), null,
				record.getPlayRecordShareUrl());
		info.imageUrl = record.getPlayRecordImageUrl();
		info.site = "100tv";
		info.siteUrl = share_link_address;
		info.countID = (int) record.getPlayRecordCID();
		info.comeFrom = 1;

		if (mShareStateListener == null) {
			mShareStateListener = new MyShareStateListener();
		}
		if (mSelectSharePopwindow == null) {
			Rect frame = new Rect();
			getActivity().getWindow().getDecorView()
					.getWindowVisibleDisplayFrame(frame); // mActivity指当前的activity
			int Height = ScreenUtil.getScreenHeightPix(getActivity())
					- rl_quick_play_video.getHeight() - frame.top;
			mSelectSharePopwindow = new SelectSharePopwindow(getActivity(),
					Height, ScreenUtil.getScreenWidthPix(getActivity()),
					mShareStateListener);
		}

		mSelectSharePopwindow.show(rl_quick_play_video, info);

	}

	// 分享的监听器
	private class MyShareStateListener implements ShareStateListener {

		@Override
		public void shareAction(int action, String info) {
			switch (action) {
			case ShareStateListener.SHARING:
				L.v(TAG, "shareAction", "SHARING");
				break;
			case ShareStateListener.SHARE_SUCCESS:
				L.v(TAG, "shareAction", "SHARE_SUCCESS");
				break;
			case ShareStateListener.SHARE_FAILED:
				L.v(TAG, "shareAction", "SHARE_FAILED");
				break;
			case ShareStateListener.SHARE_CANCEL:
				L.v(TAG, "shareAction", "SHARE_CANCEL");
				break;
			default:
				break;
			}

		}

		@Override
		public void onUserInfoComplete(SNSUserInfo user) {

		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_quick_play_video:
			break;
		case R.id.iv_quick_play_pucker:
			downOutView();
			break;
		case R.id.iv_quick_play_more:
			if (mHeaderRecord != null) {
				if (mHeaderRecord.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL
						|| mHeaderRecord.getPlayRecordType() == PlayRecord.RECORD_PLAYER_CACHE) {
					showMoreOperation(v, true, mHeaderRecord);
				} else {
					showMoreOperation(v, false, mHeaderRecord);
				}
				((ImageView) v)
						.setImageResource(R.drawable.quick_more_small_click);
			}
			break;
		case R.id.iv_quick_play_start:
			if (mHeaderRecord != null) {

				if (!isClickValid()) {// 点击是否有效
					return;
				}

				if (mHeaderRecord.getPlayRecordType() != PlayRecord.RECORD_PLAYER_CACHE) {
					gotoPlayer(mHeaderRecord, FULLPLAYER);
				} else {
					ArrayList<CacheVideo> videos = new ArrayList<CacheVideo>();
					CacheVideo video = new CacheVideo();
					String[] urls = mHeaderRecord
							.getOfflineCacheFragmentUrlArray();
					video.setUrls(urls);
					int[] durations = mHeaderRecord
							.getOfflineCacheFragmentDurationArray();
					video.setDurations(durations);
					video.setName(mHeaderRecord.getPlayRecordName());
					video.setXyzplay(mHeaderRecord.getPlayRecordPlayUrl());
					video.setPic(mHeaderRecord.getPlayRecordImageUrl());
					video.setDownFinish(true);
					videos.add(video);
					if (getActivity() != null) {
						FoneUtil.openCacheVideo(getActivity(),
								PlayerFrom.CACHE_LIST, videos, 0);
					}
				}
			}
			break;
		case R.id.tv_go_online:
			CallBack.showOnlineFragment();
			break;
		case R.id.tv_login_tip:
			Intent intent = new Intent();
			intent.setClass(ApplicationManage.getGlobalContext(),
					LoginActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	// 展示更多操作的popWindow
	private void showMoreOperation(final View view, boolean isLocal,
			final PlayRecord record) {
		L.i(TAG, "showMoreOperation", "record:" + record);
		if (record.getPlayRecordType() == PlayRecord.RECORD_WEB_NETWORK
				|| record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL) {
			// 如果是网络视频 或者是本地视频
			isLocal = true;
		}
		QuickPlayMoreOperationPopWindow popWindow = new QuickPlayMoreOperationPopWindow(
				getActivity(), isLocal);
		popWindow.setOperationListener(new IMoreOperationListener() {

			@Override
			public void share() {
				showSharePopWindow(record);
			}

			@Override
			public void getDetail() {
				doDetail(record);
			}

			@Override
			public void delete() {
				isDeleteHeader = true;
				doDelete(mHeaderRecord, null, -1);
			}

			@Override
			public void collect() {
				doCollection(mHeaderRecord);
			}

			@Override
			public void dismiss() {// popwindow消失的时候调用
				((ImageView) view)
						.setImageResource(R.drawable.quick_more_small);
			}
		});
		popWindow.showPopupWindow(view, isLocal);
	}

	// 添加播放记录
	public static synchronized void addRecord(PlayRecord playrecord) {

		L.i(TAG, "addRecord:", "Playrecord:" + playrecord.toString());

		PlayRecord record = playrecord;

		if (TextUtils.isEmpty(record.getPlayRecordDetailUrl())
				&& !TextUtils.isEmpty(record.getPlayRecordPlayUrl())) {
			String detailUrl = record.getPlayRecordPlayUrl().replaceFirst(
					"xyzplay", "vgdetail");
			L.v(TAG, "addRecord", "detailUrl : " + detailUrl);
			record.setPlayRecordDetailUrl(detailUrl);
		}

		if (record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL
				|| record.getPlayRecordType() == PlayRecord.RECORD_WEB_NETWORK
				|| record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_CACHE) {// 为本地视频
			if (record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL
					|| record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_CACHE) {
				if (record.getPlayRecordPlayUrl().startsWith("file://")) {
					String url = record.getPlayRecordPlayUrl().replace(
							"file://", "");
					L.v(TAG, "url=" + url);
					File file = new File(url);
					if (file.exists()) {
						try {
							String filePath = file.getCanonicalPath();
							L.v(TAG, "getCanonicalPath=" + filePath);
							if (filePath
									.startsWith("/storage/emulated/legacy/")) {
								url = filePath.replaceFirst(
										"/storage/emulated/legacy/",
										"/storage/emulated/0/");
							}
							L.v(TAG, "filePath=" + url);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					record.setPlayRecordPlayUrl(url);
				}
				int progress = (int) ((float) (record
						.getPlayRecordAlreadyPlayTime())
						/ (float) (record.getPlayRecordTotalTime()) * 100);

				MainTabActivity.setRoundButtonImage(
						record.getPlayRecordImageUrl(), true, progress);// 设置中间按钮图片
			}
			if (record.getPlayRecordType() == PlayRecord.RECORD_WEB_NETWORK) {
				record.setPlayRecordPlayUrl(record.getPlayRecordName());
			}
			StorageModule.getInstance().addPlayRecord(record);

			if (f != null) {
				L.v(TAG, "addRecord", " PlayRecordFragment is foreground : "
						+ f.foreground);
				if (f.foreground) {
					f.initData();
				}
			}

		} else {
			// 添加到数据库
			record.setPlayRecordSynchronzieType(PlayRecord.PLAY_RECORD_SYNCHRONZIE_ADD_WAIT);
			StorageModule.getInstance().addPlayRecord(record);

			if (f != null) {
				L.v(TAG, "addRecord", " PlayRecordFragment is foreground : "
						+ f.foreground);
				if (f.foreground) {
					f.initData();
				}
			}

			int progress = (int) ((float) (record
					.getPlayRecordAlreadyPlayTime())
					/ (float) (record.getPlayRecordTotalTime()) * 100);

			MainTabActivity.setRoundButtonImage(record.getPlayRecordImageUrl(),
					false, progress);// 设置中间按钮图片

			if (UserInfoManager.isLogin()
					&& FoneUtil.isNetOk(ApplicationManage.getGlobalContext())) {
				if (mAddList == null) {
					mAddList = new ArrayList<PlayRecord>();
				}
				// 向服务器同步
				RecordData data = new RecordData();
				data.ccid = record.getPlayRecordCCID();
				data.cid = record.getPlayRecordCID();
				data.clid = record.getPlayRecordCLID();
				data.videoid = record.getPlayRecordVideoID();
				data.type = 1;
				data.secs = record.getPlayRecordTotalTime();
				data.tp = record.getPlayRecordAlreadyPlayTime();
				data.updatetime = record.getPlayRecordCreateTime();
				List<RecordData> list = new ArrayList<RecordData>();
				list.add(data);
				mAddList.add(record);
				addQuickPlayCallBack addCallBack = new addQuickPlayCallBack();
				Request.getInstance().collection(list, 1, 2, 0, 0, addCallBack);
			}
		}
	}

	private void doDelete(final PlayRecord record, final View ItemView,
			final int index) {

		LocalDeleteMediaDialog deleteDialog = new LocalDeleteMediaDialog(
				getActivity(), "确定删除该内容吗?");
		deleteDialog.setListener(new IDeleteListener() {

			@Override
			public void delete() {
				if (record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL
						|| record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_CACHE) {// 本地视频，只从数据库中删除
					int result = StorageModule.getInstance().deletePlayRecord(
							record);
					L.i(TAG, "delete local result:" + result);
				} else {
					// 更改数据库该记录的状态为删除状态
					record.setPlayRecordSynchronzieType(PlayRecord.PLAY_RECORD_SYNCHRONZIE_DELETE_WAIT);
					int updateresult = StorageModule.getInstance()
							.updatePlayRecord(record);
					L.i(TAG, "delete", "updateresult:" + updateresult);
					if (UserInfoManager.isLogin()
							&& FoneUtil.isNetOk(getActivity())) {
						if (mDeleteList == null) {
							mDeleteList = new ArrayList<PlayRecord>();
						}
						L.i(TAG, "doDelete", "record:" + record);
						mDeleteList.add(record);
						// 从服务器删除
						// 截取furl中的数据
						List<RecordData> updateInfo = new ArrayList<RecordData>();
						RecordData data = new RecordData();
						String furl = record.getPlayRecordPlayUrl();
						getParams(data, furl);
						data.type = 2;
						data.ccid = record.getPlayRecordCCID();
						data.cid = record.getPlayRecordCID();
						data.clid = record.getPlayRecordCLID();
						data.secs = record.getPlayRecordTotalTime();
						data.tp = record.getPlayRecordAlreadyPlayTime();
						data.videoid = record.getPlayRecordVideoID();
						updateInfo.add(data);
						deleteCallBack = new deleteQuickPlayCallBack();
						Request.getInstance().collection(updateInfo, 2, 2, 0,
								0, deleteCallBack);
					}
				}
				if (mHistoryRecords.size() > 0) {
					int position = lv_quick_play_video
							.getFirstVisiblePosition();
					if (index > position) {
						position = index;
					}
					View view = null;
					if (index == -1) {
						if (lv_quick_play_video.getHeaderViewsCount() != 0) {
							view = lv_quick_play_video.getChildAt(1);
						} else {
							view = lv_quick_play_video.getChildAt(0);
						}
					} else {
						view = ItemView;
					}

					ViewHolder holder = (ViewHolder) view.getTag();
					holder.needInflate = true;
					DeleteAnimationListener deleteListener = new DeleteAnimationListener(
							index);
					deleteHistoryAnimationUtil.animHideShowView(view,
							deleteListener, 0, false, 500);
				} else {
					// Bitmap bm =
					// BitmapFactory.decodeResource(ApplicationManage
					// .getGlobalContext().getResources(),
					// R.drawable.home_quick_play_surface_default);
					// @SuppressWarnings("deprecation")
					// Drawable mQuickPlayBg = new BitmapDrawable(RoundImageUtil
					// .toRoundBitmap(bm));
					// MainTabActivity.mPlayLayout
					// .setBackgroundDrawable(mQuickPlayBg);

					MainTabActivity.mPlayLayout
							.setBackgroundResource(R.drawable.home_quick_play_surface_default);

					MainTabActivity.mQuickPlayBtn.setProgress(0);

					SharedPreferenceModule.getInstance().setBoolean(
							"play_record_local_url", false);
					SharedPreferenceModule.getInstance().setString(
							"play_record_url", "");
					SharedPreferenceModule.getInstance().setInt(
							"play_record_progress", 0);

					showNoRecordView();
				}
			}
		});
	}

	// 从furl上截取参数
	public void getParams(RecordData data, String furl) {
		String stringlist[] = furl.substring(furl.indexOf("?") + 1).split("&");
		for (int i = 0; i < stringlist.length; i++) {
			if (stringlist[i].startsWith("cid=")) {

				data.cid = FoneUtil.String2Long(stringlist[i]
						.substring(stringlist[i].indexOf("=") + 1));
			}
			if (stringlist[i].startsWith("ccid=")) {
				data.ccid = FoneUtil.String2Long(stringlist[i]
						.substring(stringlist[i].indexOf("=") + 1));
			}
			if (stringlist[i].startsWith("videoid=")) {
				data.videoid = FoneUtil.String2Long(stringlist[i]
						.substring(stringlist[i].indexOf("=") + 1));
			}
			if (stringlist[i].startsWith("clid=")) {
				data.clid = FoneUtil.String2Long(stringlist[i]
						.substring(stringlist[i].indexOf("=") + 1));
			}
		}
	}

	// 页面向下执行动画 退出
	public void downOutView() {
		if (getActivity() == null) {
			L.i(TAG, "null null null null null null null!");
			return;
		}
		Animation downAnima = AnimationUtils.loadAnimation(getActivity(),
				R.anim.push_down_out);
		downAnima.setFillAfter(true);
		mView.startAnimation(downAnima);
		downAnima.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				CallBack.remove();
			}
		});
	}

	private class deleteQuickPlayCallBack implements Callback<CollectionRst> {

		@Override
		public void onSuccess(CollectionRst t) {
			L.i(TAG, "deleteQuickPlayCallBack:  t:" + t.toString());
			int index = -1;
			if (t != null && t.result == 0) {
				if (mDeleteList != null) {
					for (int i = 0; i < mDeleteList.size(); i++) {
						PlayRecord record = mDeleteList.get(i);
						L.i(TAG, "deleteQuickPlayCallBack record:",
								record.toString());
						long id = record.getPlayRecordVideoID();
						if (id == t.videoid) {
							index = i;
							int deleteResult = StorageModule.getInstance()
									.deletePlayRecord(record);
							L.i(TAG, "deleteQuickPlayCallBack record:",
									"deleteResult:" + deleteResult);
							// checkLocalDB();
							// FoneUtil.showToast(getActivity(), "删除成功");
							break;
						}
					}
					if (index != -1) {
						mDeleteList.remove(index);
					}
				}
			}
		}

		@Override
		public void onFailure(Error error) {
			L.i(TAG, "deleteQuickPlayCallBack:  error:" + error.toString());
			FoneUtil.showToast(getActivity(), "删除失败");
		}

	}

	private static class addQuickPlayCallBack implements
			Callback<CollectionRst> {

		@Override
		public void onSuccess(CollectionRst t) {
			L.i(TAG, "collection success: rst.videoid=" + t.videoid);
			L.i(TAG, "collection success: rst=" + t.toString());
			int index = -1;
			if (t.result == 0) {
				if (mAddList != null) {
					for (int i = 0; i < mAddList.size(); i++) {
						PlayRecord record = mAddList.get(i);
						long id = record.getPlayRecordVideoID();
						if (id == t.videoid) {
							index = i;
							record.setPlayRecordSynchronzieType(PlayRecord.PLAY_RECORD_SYNCHRONZIE_ADD_ALREADY);
							StorageModule.getInstance()
									.updatePlayRecord(record);
							// FoneUtil.showToast(
							// ApplicationManage.getGlobalContext(),
							// "添加成功!");
							L.v(TAG, "添加播放记录成功");
							break;
						}
					}
				}
				if (index != -1) {
					mAddList.remove(index);
				}
			}
		}

		@Override
		public void onFailure(Error error) {

			if (error != null) {
				L.e(TAG, "addQuickPlayCallBack",
						"onFailure start error=" + error.toString());
			}

		}

	}

	private class DeleteAnimationListener implements AnimationListener {
		private int index;

		public DeleteAnimationListener(int index) {
			this.index = index;
		}

		@Override
		public void onAnimationStart(Animation animation) {

		}

		@Override
		public void onAnimationEnd(Animation animation) {
			if (index == -1) {
				mHeaderRecord = mHistoryRecords.remove(0);
			} else {
				mHistoryRecords.remove(index);
			}
			if (isDeleteHeader) {
				fillHeaderView();
				isDeleteHeader = false;
			}
			mAdapter.notifyDataSetChanged();
			if (mHistoryRecords.size() == 0) {
				lv_quick_play_video.setVisibility(View.GONE);
			}
		}

		@Override
		public void onAnimationRepeat(Animation animation) {

		}
	}

	// 访问网络 返回接口
	private class QuickPlayCallBack implements Callback<CollectionlsRst> {

		@Override
		public void onSuccess(CollectionlsRst t) {
			// pb.setVisibility(View.GONE);
			loadView.setVisibility(View.GONE);
			loadingView.setVisibility(View.GONE);
			L.i(TAG, "QuickPlayCallBack  success!");
			if (t.result == SUCCESS) {
				// 清空本地数据库中的在线播放记录
				StorageModule.getInstance().deletePlayRecordList(
						PlayRecord.RECORD_WEB_ALL);
				List<Cnt> cntList = t.cnts.cntList;
				if (t == null || t.cnts == null || t.cnts.cntList == null) {
					L.i(TAG, "QuickPlayCallBack:t1=" + t);
					if (foreground) {// 如果在前台做刷新
						doRefrushRecord();
					}
					return;
				} else {
					L.i(TAG, "QuickPlayCallBack:t2=" + t);
					// if (result == 1) { 数据库为空时 返回-1
					List<PlayRecord> list = new ArrayList<PlayRecord>();
					if (mNeedRefrushRecordFomeServer) {
						fillList(list, mHistoryRecords, cntList, t.host,
								t.shost);
						if (mHeaderRecord != null) {
							mHistoryRecords.remove(mHeaderRecord);
							mHistoryRecords.add(mHeaderRecord);
						}
					} else {
						fillList(list, null, cntList, t.host, t.shost);
					}
					StorageModule.getInstance().addPlayRecordList(list);
					// checkLocalDB();
					// }
					if (mNeedRefrushRecordFomeServer) {
						noRecordView.setVisibility(View.GONE);
						recordView.setVisibility(View.VISIBLE);

						if (mHistoryRecords.size() > 0) {
							noRecordView.setVisibility(View.GONE);
							lv_quick_play_video.setVisibility(View.VISIBLE);
							SortListUtil.sortHistoryRecord(mHistoryRecords);
							limitPlayRecords(mHistoryRecords);
							mHeaderRecord = mHistoryRecords.remove(0);
						} else if (mHistoryRecords.size() == 0) {
							showNoRecordView();
						}
						if (mHistoryRecords.size() > 0) {
							showClearButton(true);
						} else {
							showClearButton(false);
						}
						mAdapter.notifyDataSetChanged();
						if (foreground) {// 如果在前台做刷新
							fillHeaderView();
						}
					}
				}
			} else {
				L.i(TAG, "QuickPlayCallBack:t3=" + t);
				FoneUtil.showToast(getActivity(), "获取内容失败，请重试");
				if (foreground) {// 如果在前台做刷新
					doRefrushRecord();
				}
			}
		}

		@Override
		public void onFailure(Error error) {
			// pb.setVisibility(View.GONE);
			loadView.setVisibility(View.GONE);
			loadingView.setVisibility(View.GONE);
			if (foreground) {
				doRefrushRecord();
			}
			if (error != null) {
				L.i(TAG, "QuickPlayCallBack   error.state:" + error.getStatus());
				L.i(TAG,
						"QuickPlayCallBack   error.reason:" + error.getReason());
				if (error.isNetworkError()) {
					FoneUtil.showToast(getActivity(), "网络超时,请稍后重试");
				} else {
					FoneUtil.showToast(getActivity(), "获取内容失败，请重试");
				}
			}
		}
	}

	public interface IPlayFragmentCallBack {
		void remove();

		void showOnlineFragment();
	}

	// private void checkLocalDB() {

	// L.v("JasonZue",
	// "数据库中数据 playRecordList"
	// + StorageModule
	// .getInstance()
	// .getPlayRecordList(
	// PlayRecord.RECORD_PLAYER_NETWORK)
	// .toString());

	// ArrayList<PlayRecord> playRecordList =
	// StorageModule.getInstance().getPlayRecordList(PlayRecord.RECORD_WEB_ALL);
	// for (PlayRecord playRecord : playRecordList) {
	// System.out.println(playRecord.getPlayRecordName() + "####"
	// +playRecord.getPlayRecordCID());
	// }

	// }

	// 将cntList中的对象转换为PlayRecord放入到list、historys中
	public void fillList(List<PlayRecord> list, List<PlayRecord> historys,
			List<Cnt> cntList, String host, String shost) {
		for (Cnt cnt : cntList) {
			cnt.pic = FoneUtil.getAbsoluteUrl(host, shost, cnt.pic);
			PlayRecord record = new PlayRecord();
			record.setPlayRecordDetailUrl(cnt.durl);

			if (cnt.toply == 1) {
				record.setPlayRecordType(PlayRecord.RECORD_WEB_SOURCE);
			} else {
				record.setPlayRecordType(PlayRecord.RECORD_PLAYER_NETWORK);
			}

			record.setPlayRecordName(cnt.name);
			record.setPlayRecordImageUrl(cnt.pic);
			record.setPlayRecordRemoveUrl(cnt.rurl);
			record.setPlayRecordTotalTime(cnt.mins);
			record.setPlayRecordAlreadyPlayTime(cnt.tp);
			record.setPlayRecordContentType(cnt.type);
			record.setPlayRecordVideoID(cnt.videoid);
			record.setPlayRecordCreateTime(cnt.udate);
			record.setPlayRecordCCID(FoneUtil.String2Long(FoneUtil
					.getCCIdByUrl(cnt.url)));
			record.setPlayRecordCID(FoneUtil.String2Long(FoneUtil
					.getCIdByUrl(cnt.url)));
			record.setPlayRecordCLID(FoneUtil.String2Long(FoneUtil
					.getCLIdByUrl(cnt.url)));
			record.setPlayRecordEpisodeUpdateInfo(cnt.updateinfo);
			record.setPlayRecordSynchronzieType(PlayRecord.PLAY_RECORD_SYNCHRONZIE_ADD_ALREADY);
			cnt.weibourl = FoneUtil.getAbsoluteUrl(host, shost, cnt.weibourl);
			record.setPlayRecordShareUrl(cnt.weibourl);
			record.setPlayRecordPlayUrl(cnt.url);
			record.setPlayRecordIsVIP(cnt.vip == 1);
			record.setPlayRecordExternalUrl(cnt.ourl);
			record.setPlayRecordIsShowPlayButton(cnt.btnply == 1 ? true : false);

			if (list != null) {
				list.add(record);
			}
			if (historys != null) {
				historys.add(record);
			}
		}
	}

	private class clearListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			String quick_play_clear_all = getActivity().getResources()
					.getString(R.string.quick_play_clear_all);
			LocalDeleteMediaDialog dialog = new LocalDeleteMediaDialog(
					getActivity(), quick_play_clear_all);
			dialog.setListener(new IDeleteListener() {

				@Override
				public void delete() {
					mHistoryRecords.clear();
					mAdapter.notifyDataSetChanged();
					mHeaderRecord = null;
					fillHeaderView();
					showNoRecordView();
					showClearButton(false);
					// 清空数据库和服务(先删除本地视频的记录 该记录不用跟服务器同步)
					StorageModule.getInstance().deletePlayRecordList(
							PlayRecord.RECORD_PLAYER_LOCAL);
					StorageModule.getInstance().deletePlayRecordList(
							PlayRecord.RECORD_PLAYER_CACHE);

					ArrayList<PlayRecord> list = StorageModule.getInstance()
							.getPlayRecordList(PlayRecord.RECORD_WEB_ALL);
					for (int i = 0; i < list.size(); i++) {
						list.get(i).setPlayRecordSynchronzieType(
								PlayRecord.PLAY_RECORD_SYNCHRONZIE_DELETE_WAIT);
					}
					// Drawable drawable = getActivity().getResources()
					// .getDrawable(R.drawable.default_image_bg);
					// BitmapDrawable bd = (BitmapDrawable) drawable;
					// Bitmap bm = bd.getBitmap();

					// Bitmap bm =
					// BitmapFactory.decodeResource(ApplicationManage
					// .getGlobalContext().getResources(),
					// R.drawable.home_quick_play_surface_default);
					// @SuppressWarnings("deprecation")
					// Drawable mQuickPlayBg = new BitmapDrawable(RoundImageUtil
					// .toRoundBitmap(bm));
					// MainTabActivity.mPlayLayout
					// .setBackgroundDrawable(mQuickPlayBg);

					MainTabActivity.mPlayLayout
							.setBackgroundResource(R.drawable.home_quick_play_surface_default);

					StorageModule.getInstance().updatePlayRecordList(list);
					if (UserInfoManager.isLogin()
							&& FoneUtil.isNetOk(getActivity())) {

						Request.getInstance().collection(null, 3, 2, 0, 0,
								new Callback<CollectionRst>() {

									@Override
									public void onSuccess(CollectionRst t) {
										L.i(TAG, "btn_clear_all success:"
												+ t.result);
										if (t.result == 0) {
											StorageModule
													.getInstance()
													.deletePlayRecordList(
															PlayRecord.RECORD_WEB_ALL);
											FoneUtil.showToast(getActivity(),
													"清空成功！");
										}
									}

									@Override
									public void onFailure(Error error) {
										L.i(TAG,
												"btn_clear_all error:"
														+ error.toString());
									}
								});
					}
				}
			});

		}
	}

	// 是否展示清空按钮
	public void showClearButton(boolean isShow) {
		if (btn_clear_all != null && lv_quick_play_video != null) {
			if (!isShow) {
				btn_clear_all.setVisibility(View.GONE);
				if (lv_quick_play_video.getFooterViewsCount() > 1) {
					lv_quick_play_video.removeFooterView(btn_clear_all);
				}
			} else {
				btn_clear_all.setVisibility(View.VISIBLE);
				if (lv_quick_play_video.getFooterViewsCount() < 1) {
					lv_quick_play_video.addFooterView(btn_clear_all);
				}
			}
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	/**
	 * 添加收藏操作
	 * 
	 * @param furl
	 * @return void
	 * @throws
	 */

	private void doCollection(PlayRecord record) {
		// 截取furl中的数据
		L.i(TAG, "doCollection", "Record:" + record.toString());
		List<RecordData> updateInfo = new ArrayList<RecordData>();
		RecordData data = new RecordData();
		data.ccid = record.getPlayRecordCCID();
		data.cid = record.getPlayRecordCID();
		data.videoid = record.getPlayRecordVideoID();
		data.clid = record.getPlayRecordCLID();
		data.type = 1;
		data.ifp = 2;
		String time = System.currentTimeMillis() + "";
		time = time.substring(5);
		data.updatetime = Integer.valueOf(time);
		data.secs = record.getPlayRecordTotalTime();
		data.tp = record.getPlayRecordAlreadyPlayTime();
		if (StorageModule.getInstance().isFavourite(data.videoid)) {
			// 如果收藏中有该条记录 不操作
			FoneUtil.showToast(getActivity(), "已存在于收藏列表中");
			return;
		}

		updateInfo.add(data);
		// 添加记录到数据库 type=1 提示用户收藏成功
		FoneUtil.showToast(getActivity(), "已加入到收藏");

		// 离线添加数据到数据库,信息不全,该条数据如果在有网络能同步上以后才可显示.
		OfflineCache offlineCache = new OfflineCache();
		offlineCache.setCacheCCID(data.ccid);
		offlineCache.setCacheCID(data.cid);
		offlineCache.setCacheCLID(data.clid);
		offlineCache.setCacheVideoId(data.videoid);
		offlineCache.setCacheName(record.getPlayRecordName());
		offlineCache.setCacheDetailUrl(record.getPlayRecordDetailUrl());
		offlineCache.setCacheCreateTime(Integer.valueOf(time));
		offlineCache.setCacheImageUrl(record.getPlayRecordImageUrl());
		offlineCache.setCacheIsDelete(false);
		offlineCache.setCacheIsDownlaod(false);
		offlineCache
				.setCacheSynchronzieType(OfflineCache.CACHE_FAVOURITE_SYNCHRONZIE_ADD_WAIT);
		offlineCache.setCacheContentType(record.getPlayRecordContentType());
		offlineCache.setCacheXYZPlayUrl(record.getPlayRecordPlayUrl());
		offlineCache.setCacheReportPage(2);
		offlineCache.setCacheIsVip(record.getPlayRecordIsVIP());

		// 发送添加收藏请求
		if (UserInfoManager.isLogin()) {
			AddCollectionCallback collectionCallback = new AddCollectionCallback();
			collectionCallback.setOfflineCache(offlineCache);
			Request.getInstance().collection(updateInfo, 1, 1, 0, 0,
					collectionCallback);
		}
		L.i(TAG, "doCollection", "offlineCache:" + offlineCache.toString());
		StorageModule.getInstance().addFavourite(offlineCache);
	}

	private class AddCollectionCallback implements
			com.fone.player.client.Callback<CollectionRst> {
		private OfflineCache offlineCache;

		public void setOfflineCache(OfflineCache offlineCache) {

			this.offlineCache = offlineCache;
		}

		@Override
		public void onSuccess(CollectionRst t) {
			// FoneUtil.showToast(getActivity(), "测试用:添加云端收藏数据成功,本地也成功");
			L.v("JasonZue", "添加收藏结果" + t.toString());
			// 修改对应 videoId的type数值 1->0
			if (t.result == 0) {
				offlineCache.setCacheSynchronzieType(0);
				StorageModule.getInstance().updateFavouriteSynchronzieType(
						offlineCache);
			} else {
				FoneUtil.showToast(getActivity(), "云端收藏失败,已收藏至本地");
				Reporter.logError(offlineCache.getCacheCID() + "", 4);
			}
		}

		@Override
		public void onFailure(Error error) {
			L.v(TAG, "AddCollectionCallback onFailure", "isNetworkError : "
					+ error.isNetworkError() + " status : " + error.getStatus()
					+ " reason : " + error.getReason());
			// FoneUtil.showToast(getActivity(), "测试用:添加云端收藏数据失败,本地成功");
			Reporter.logError(offlineCache.getCacheCID() + "", 4);
		}

	}

	// 用于把页面上的快速播放的按钮传过来进行赋值
	// public void setQuickPlayImageView(RoundImageView QuickPlayImageView) {
	// this.mQuickPlayImageView = QuickPlayImageView;
	// }

	// 限制播放记录最多20条
	private void limitPlayRecords(List<PlayRecord> playRecords) {
		if (playRecords.size() > MAXNUM) {
			List<PlayRecord> DeleteList = new ArrayList<PlayRecord>();
			while (mHistoryRecords.size() > MAXNUM) {
				PlayRecord deleteRecord = mHistoryRecords
						.remove(mHistoryRecords.size() - 1);
				DeleteList.add(deleteRecord);
			}

			if (DeleteList != null) {
				List<PlayRecord> tempDeleteList = new ArrayList<PlayRecord>();
				for (PlayRecord record : DeleteList) {
					if (record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL) {
						StorageModule.getInstance().deletePlayRecord(record);
					} else if (record.getPlayRecordType() == PlayRecord.RECORD_PLAYER_NETWORK
							|| record.getPlayRecordType() == PlayRecord.RECORD_WEB_SOURCE) {
						record.setPlayRecordSynchronzieType(PlayRecord.PLAY_RECORD_SYNCHRONZIE_DELETE_WAIT);
						tempDeleteList.add(record);
					}
				}
				if (tempDeleteList != null && tempDeleteList.size() > 0) {
					StorageModule.getInstance().updatePlayRecordList(
							tempDeleteList);
					if (UserInfoManager.isLogin()
							&& FoneUtil.isNetOk(getActivity())) {
						for (PlayRecord record : tempDeleteList) {
							if (mDeleteList == null) {
								mDeleteList = new ArrayList<PlayRecord>();
							}
							mDeleteList.add(record);
							// 从服务器删除
							// 截取furl中的数据
							List<RecordData> updateInfo = new ArrayList<RecordData>();
							RecordData data = new RecordData();
							String furl = record.getPlayRecordPlayUrl();
							getParams(data, furl);
							data.type = 2;
							data.ccid = record.getPlayRecordCCID();
							data.cid = record.getPlayRecordCID();
							data.clid = record.getPlayRecordCLID();
							data.secs = record.getPlayRecordTotalTime();
							data.tp = record.getPlayRecordAlreadyPlayTime();
							updateInfo.add(data);
							if (deleteCallBack == null) {
								deleteCallBack = new deleteQuickPlayCallBack();
							}
							Request.getInstance().collection(updateInfo, 2, 2,
									1000, 0, deleteCallBack);
						}

					}
				}
			}
		}
	}

	@Override
	public void onPause() {
		foreground = false;
		super.onPause();
	}

	@Override
	public void onResume() {
		foreground = true;
		FoneUtil.isNetOkWithToast(getActivity());
		initData();
		L.i(TAG, "onresume!!!!!!!!!!!!!!!!!!!!");
		super.onResume();
	}

	private void initMyData(boolean needRefrushFromServer) {
		L.i(TAG, "needRefrushFromServer" + needRefrushFromServer);
		mHeaderRecord = null;
		if (!needRefrushFromServer) {
			getRecordfromDB(PlayRecord.RECORD_PLAYER_LOCAL);
			getRecordfromDB(PlayRecord.RECORD_PLAYER_CACHE);
			// if (UserInfoManager.isLogin()) {
			getRecordfromDB(PlayRecord.RECORD_WEB_ALL);
			// }
			if (UserInfoManager.isLogin() && FoneUtil.isNetOk(getActivity())) {// 如果已经登陆
				getRecordformServer();// 向服务器同步
			}
			mHistoryRecords.clear();
			mHistoryRecords.addAll(mTempHistoryRecords);
			L.i(TAG, "initMyData", "mHistoryRecords:" + mHistoryRecords);

			mTempHistoryRecords.clear();
			doRefrushRecord();
		} else {
			getRecordfromDB(PlayRecord.RECORD_PLAYER_LOCAL);
			getRecordfromDB(PlayRecord.RECORD_PLAYER_CACHE);
			mHistoryRecords.clear();
			mHistoryRecords.addAll(mTempHistoryRecords);
			mTempHistoryRecords.clear();
			if (UserInfoManager.isLogin() && FoneUtil.isNetOk(getActivity())) {// 如果已经登陆
				getRecordformServer();
			} else {
				// 如果没有登陆，取出数据库中所有的播放记录
				getRecordfromDB(PlayRecord.RECORD_WEB_ALL);
				mHistoryRecords.addAll(mTempHistoryRecords);
				mTempHistoryRecords.clear();
				doRefrushRecord();
			}
			L.i(TAG, "initMyData", "mHistoryRecords:" + mHistoryRecords);

		}
	}

	private void doRefrushRecord() {
		if (mHistoryRecords.size() == 0 && mHeaderRecord == null) {
			showNoRecordView();
		} else {
			noRecordView.setVisibility(View.GONE);
			recordView.setVisibility(View.VISIBLE);
		}
		if (mHeaderRecord != null) {
			mHistoryRecords.add(mHeaderRecord);
		}

		if (mHistoryRecords.size() > 0) {
			noRecordView.setVisibility(View.GONE);
			lv_quick_play_video.setVisibility(View.VISIBLE);
			SortListUtil.sortHistoryRecord(mHistoryRecords);
			limitPlayRecords(mHistoryRecords);
			mHeaderRecord = mHistoryRecords.remove(0);
			fillHeaderView();
		}
		if (mHistoryRecords.size() == 0) {
			btn_clear_all.setVisibility(View.GONE);
		} else {
			btn_clear_all.setVisibility(View.VISIBLE);
		}

		L.i(TAG, "观看记录：historyPlayRecord size:" + mHistoryRecords.size());

		mAdapter.notifyDataSetChanged();
	}

	/**
	 * 点击是否有效
	 * 
	 * @return
	 */
	private boolean isClickValid() {
		long currentTime = System.currentTimeMillis();
		if (currentTime - preClickTime < 1000) {
			L.v(TAG, " isClickValid ", " false ");
			return false;
		} else {
			preClickTime = currentTime;
			L.v(TAG, " isClickValid ", " true ");
			return true;
		}
	}
}
